<template>
  <div>
    <!-- 来源渠道弹窗 -->
    <BaseDialog
      title="来源渠道查询"
      :visible.sync="visibleSource"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <sourceMadal
        ref="addDialogRef"
        selectType="single"
        v-model="this.clueSource"
        @close="closeSource"
      />
    </BaseDialog>
    <el-form
      ref="form"
      :model="form"
      inline
      size="mini"
      :disabled="this.type1==='detail'"
      label-width="90px"
    >
      <!-- 职位 -->
      <div>
        <h3 class="duty">职位</h3>
        <h3 class="padL10 postH3" @click="handleShow('edit')">
          {{pointName}}
          <span v-show="!dutyRole?false:true">({{dutyRole}})</span>
        </h3>
      </div>
      <!-- 责任线索来源 -->
      <!-- <div v-if="this.dataType == 10461003?true:false">
        <h3 class="duty">责任线索来源</h3>
        <h3 class="padL10 postH3">
          <FormPanel
            :list="initSourceForm"
            :cols="20"
            formType="edit"
            :labelWidth="90"
            :isSubmitBtn="false"
            class="mtop"
          />
        </h3>
      </div> -->
      <!-- 职责 -->
      <!-- <div v-if="!emIsShow" class="dutyWrap">
        <h3 class="duty">角色属性</h3>
        <div class="padL10">
          <p style="float: left;margin-right: 35px;">销售</p>
          <el-checkbox-group v-model="checkedList1" disabled @change="handleCheckedChange">
            <el-checkbox
              v-for="role in sites"
              :label="role.codeId"
              :key="role.codeId+'C'"
              :value="role.codeId"
            >{{role.codeCnDesc}}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="padL10">
          <p style="float: left;margin-right: 35px;">售后</p>
          <el-checkbox-group v-model="checkedList2" disabled @change="handleCheckedChange2">
            <el-checkbox
              v-for="role in sites2"
              :label="role.codeId"
              :key="role.codeId+'C'"
              :value="role.codeId"
            >{{role.codeCnDesc}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div> -->

      <!-- //CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START -->
      <!-- <div v-else class="dutyWrap">
            <h3 class='duty '>角色属性</h3>
      <div  class="padL10 " >-->
      <!-- <p style="float: left;margin-right: 35px;">销售</p> -->
      <!-- <el-checkbox-group v-model="checkedListAll"  @change="handleCheckedChangeAll" >
                  <el-checkbox v-for="role in sitesList" :label="role.codeId" :key="role.codeId+'C'" :value="role.codeId">{{role.codeCnDesc}}</el-checkbox>
                </el-checkbox-group>
            </div>
      </div>-->
      <!-- //CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END -->
      <!-- 权限管理 -->
      <el-row style="display:flex;flex-direction: column">
        <el-row style="height: 495px">
          <el-col style="height: 450px;width: 33%;">
            <div class="menu-header">菜单权限</div>
            <el-scrollbar style="height: 450px;border: 1px solid rgba(144,147,153,.5);">
              <el-col style="padding: 5px 3px;">
                <el-tree
                  ref="tree"
                  style="margin-top: 12px;"
                  v-loading="loading"
                  show-checkbox
                  :data="jsonTree"
                  node-key="id"
                  highlight-current
                  @node-click="nodeClickHandle"
                  :expand-on-click-node="false"
                />
              </el-col>
            </el-scrollbar>
          </el-col>
          <el-col style="height: 450px;width: 33%;">
            <div class="menu-header">客户信息操作权限</div>
            <el-scrollbar
              style="height: 450px;border: 1px solid rgba(144,147,153,.5);border-left: none;border-right: none;"
            >
              <el-col style="padding: 5px 3px;">
                <div>
                  <div v-loading="rangeloading">
                    <div>
                      <label>操作权限</label>
                    </div>
                    <el-checkbox-group v-model="roleMenuRange" @change="handleRoleMenuRangeChange">
                      <div style="margin:0px 0px 0px 20px;width:20px;">
                        <el-checkbox
                          v-for="menuRange in objRange"
                          :label="menuRange.menuRangeId"
                          :key="menuRange.menuRangeId"
                          :value="menuRange.menuRangeId"
                        >{{menuRange.codeCnDesc}}</el-checkbox>
                      </div>
                    </el-checkbox-group>
                    <!-- <el-radio-group v-model="roleMenuRange" @change="handleRoleMenuRangeChange">
                          <div style="margin:0px 0px 0px 20px;width:20px;">
                            <el-radio v-for="menuRange in objRange"
                            :label="menuRange.menuRangeId"
                            :key="menuRange.menuRangeId"
                            :value="menuRange.menuRangeId">{{menuRange.codeCnDesc}}
                            </el-radio>
                          </div>
                    </el-radio-group>-->
                  </div>
                  <br />
                  <div v-loading="actionloading">
                    <div>
                      <label>操作按钮</label>
                    </div>
                    <el-checkbox-group
                      v-model="roleMenuAction"
                      @change="handleRoleMenuActionChange"
                    >
                      <div style="margin:0px 0px 0px 20px;width:20px;">
                        <el-checkbox
                          v-for="menuAction in objAction"
                          :label="menuAction.menuCuringId"
                          :key="menuAction.menuCuringId"
                          :value="menuAction.menuCuringId"
                        >{{menuAction.actionName}}</el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-col>
            </el-scrollbar>
          </el-col>
          <el-col style="height: 450px;width: 33%;">
            <div class="menu-header">个人参数配置</div>
            <el-scrollbar style="height: 450px;border: 1px solid rgba(144,147,153,.5);">
              <el-col style="padding: 5px 3px;">
              <!--   <div v-show="!emIsShow">
                  <div>
                    <Todo
                      ref="Todo"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></Todo>
                  </div>
                  <div>
                    <part
                      ref="part"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></part>
                  </div>
                   <div>
                    <storageVec
                      ref="storageVec"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></storageVec>
                  </div>
                  <div v-if="this.afterSale == 10041001?true:false">
                    <storagePart
                      ref="storagePart"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></storagePart>
                  </div>
                   <div>
                    <storageJpck
                      ref="storageJpck"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></storageJpck>
                  </div>
                  <div v-if="this.afterSale == 10041001?true:false">
                    <favorableModels
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                      ref="favorableModels"
                    ></favorableModels>
                  </div>
                  // 结算
                  <div v-if="this.afterSale == 10041001?true:false">
                    <settlement
                      ref="settlement"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></settlement>
                  </div>
                  // 维修类型
                  <div v-if="this.afterSale == 10041001?true:false">
                    <maintenanceType
                      ref="maintenanceType"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></maintenanceType>
                  </div>
                  <div v-if="this.afterSale == 10041001?true:false">
                    <Warehouse
                      ref="Warehouse"
                      v-if="userPermissionData?true:false"
                      :userPermissionData="userPermissionData"
                    ></Warehouse>
                  </div>
                </div>-->
              </el-col>
            </el-scrollbar>
          </el-col>
        </el-row>
      </el-row>
    </el-form>
    <div
      :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
    >
      <el-button @click="closeDialog('refresh')">返 回</el-button>
      <!-- <el-button type="primary" v-show="this.type1 == 'edit'" @click="reqAuth">保 存</el-button> -->
      <el-button type="primary" :loading="saveLoading" @click="reqAuth">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import {
  userPermission,
  findByEmployeeId,
  findEmployeeRoleById,
  savePermission,
  supereditpassword,
  getRole,
  getRoleId,
  getRoleData,
  getUserOrgId,
  findClueSourceids,
  saveRolePermission
} from '@/api/common/auth/employeeAuth';
import { findTcCodeByType, getRoleMenuRange, getRoleMenuAction } from '@/api/common/auth/roleManage';
import * as types from '@/api/common/auth/roleManage/types';
import { getJsonTree, codeCheck } from '@/utils/index';
import Todo from '@/pages/common/auth/roleManage/components/TodoList/Todo.vue';
import part from '@/pages/common/auth/roleManage/components/TodoList/part.vue';
import Warehouse from '@/pages/common/auth/roleManage/components/TodoList/warehouse.vue';
import storageVec from '@/pages/common/auth/roleManage/components/TodoList/storageVec.vue';
import storagePart from '@/pages/common/auth/roleManage/components/TodoList/storagePart.vue';
import storageJpck from '@/pages/common/auth/roleManage/components/TodoList/storageJpck.vue';
import favorableModels from '@/pages/common/auth/roleManage/components/TodoList/favorableModels.vue';
import _ from 'lodash';
import positionTemplate from './positionTemplate';
import sourceMadal from '@/pages/cms-common/source/indexother';
import settlement from '@/pages/common/auth/roleManage/components/TodoList/settlement.vue';
import maintenanceType from '@/pages/common/auth/roleManage/components/TodoList/MaintenanceType.vue';
export default {
  name: 'Employeeauthpanel',
  mixins: [dictionary],
  components: {
    Todo,
    part,
    storageVec,
    storagePart,
    storageJpck,
    sourceMadal,
    favorableModels,
    positionTemplate,
    settlement,
    maintenanceType,
    Warehouse
  },
  props: {
    rowData: {
      type: Object,
      default: () => ({})
    },
    UserData: {},
    treeDataName: {},
    treeDataId: {},
    type1: {
      type: String,
      default: 'edit'
    },
    emIsShow: {
      type: Boolean
    }
  },
  data() {
    this.saveData = null;
    this.checkListRoleMenuRange = [];
    this.checkListRoleMenuAction = [];
    return {
      // formList: this.createFormList(),
      pointName: '',
      clueSource: '',
      clueSourceName: '',
      title: '',
      loading: false,
      initSourceForm: this.initFormFun(),
      rangeloading: false,
      actionloading: false,
      isDisables: true,
      visible: false,
      visibleSource: false, //来源渠道是否显示
      tree: [],
      menuId: '',
      objRange: [],
      roleMenuAction: [],
      roleMenuRange: [],
      objAction: [],
      userCodeShow: true,
      dutyRole: '',
      checkedList1: [],
      checkedList2: [],
      sites: [],
      sites2: [],
      form: {},
      jsonTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      roleIdList: [],
      userPermissionData: '',
      afterSale: '',
      UserDataAll: '',
      isRoleMenuRange: false,
      sitesList: [{ codeCnDesc: '大区经理', codeId: 10061011 }],
      //<!-- //CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START -->
      checkedListAll: [],
      //<!-- //CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END -->
      potOrgId: '',
      saveLoading: false
    };
  },
  computed: {
    ...mapState('app', ['btnLoading'])

    // addBtnState() {
    //   return this.btnLoading[types.YAN_ROLE_ADD];
    // }
  },
  watch: {
    UserData() {
      console.log(this.rowData, this.UserData, 'UserData111', this.type1);
      this.init();
      this.searchTree();
      this.userPermissionData = '';
      this.objRange = [];
      this.objAction = [];
      if (this.type1 == 'addPot') {
        this.pointName = this.UserData.position;
        this.potOrgId = this.UserData.orgId;
      } else {
        this.pointName = this.rowData.position;
        this.potOrgId = this.rowData.orgId;
      }

      this.pointName = this.UserData.position;
      getRoleId(this.rowData.userOrgId).then(res => {
        console.log(res, 'res');
        res.data.forEach(x => {
          this.roleIdList.push(x);
        });
      });
    }
  },
  created() {
    this.getCookie();
    this.init();
    this.searchTree();
  },
  mounted() {
    let userOrgId = this.rowData == null ? this.UserData.userOrgId : this.rowData.userOrgId;

    findClueSourceids(userOrgId)
      .then(res => {
        this.clueSource = res.data.clueSourceIds;
        this.clueSourceName = res.data.clueSourceNames;
        this.initSourceForm.find(item => item.fieldName === 'clueSourceName').initialValue = res.data.clueSourceNames;
        console.log(res.data);
      })
      .catch(err => {});
  },
  methods: {
    //搜索数据
    initFormFun() {
      return [
        {
          type: 'INPUT',
          fieldName: 'clueSourceName',
          placeholder: '请选择',
          initialValue: '',
          unitRender: () => {
            return (
              <div>
                <el-button slot="append" icon="el-icon-search" onClick={() => this.sourceHandle()}></el-button>
                <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSourceHandle()}></el-button>
              </div>
            );
          }
        }
      ];
    },
    async init() {
      console.log(this.rowData, this.UserData, 'UserData1');
      if (this.type1 == 'addPot') {
        this.pointName = this.UserData.position;
        this.potOrgId = this.UserData.orgId;
      } else {
        this.pointName = this.rowData.position;
        this.potOrgId = this.rowData.orgId;
      }
      //getRoleId
      if (this.type1 != 'edit') {
        this.pointName = this.UserData.position;
        getRoleId(this.UserData.userOrgId).then(res => {
          res.data.forEach(x => {
            this.roleIdList.push(x);
          });
        });
      } else {
        this.pointName = this.treeDataName;
        getRoleId(this.rowData.userOrgId).then(res => {
          res.data.forEach(x => {
            this.roleIdList.push(x);
          });
        });
      }

      //getRoleData
      // getRoleData(this.roleIdList).then(res=>{
      //   console.log(res,"getRoleData")
      // })
      // //职位
      // getRole(this.rowData.employeeNo,this.rowData.orgId).then(res => {
      //   res.data.forEach(x=>{
      //     this.rowData.roleId.forEach(ele=>{
      //       if(ele == x.roleId){
      //         console.log(x.roleName,"roleName")
      //         this.dutyRole+=x.roleName+","
      //       }
      //     })
      //   })
      // })

      //多选职责--售前
      await findTcCodeByType(1006).then(res => {
        this.sites = _.cloneDeep(res.data);
      });
      //  if(this.afterSale == 10041001){
      //多选职责--售后
      await findTcCodeByType(1007).then(res => {
        this.sites2 = _.cloneDeep(res.data);
      });
      //  }

      // console.log(this.UserData,"this.UserData")
      if (this.type1 != 'edit') {
        // await getUserOrgId(this.UserData.userOrgId).then(res => {
        //   res.data.before.forEach(x => [this.checkedList1.push(x.positionCode)]);
        //   res.data.after.forEach(x => [this.checkedList2.push(x.positionCode)]);
        // });
      } else {
        // this.checkedList1 = [];
        // this.checkedList2 = [];
        // await getUserOrgId(this.rowData.userOrgId).then(res => {
        //   console.log(res, '角色');

        //   res.data.before.forEach(x => [this.checkedList1.push(x.positionCode)]);
        //   res.data.after.forEach(x => [this.checkedList2.push(x.positionCode)]);
        // });
      }
    },
    getCookie() {
      let allCookie = document.cookie.split(';');
      console.log('ccc', allCookie);

      allCookie.forEach(x => {
        if (x.indexOf('dataType') > -1) {
          this.dataType = x.split('=')[1];
        }

        if (x.indexOf('afterSale') > -1) {
          this.afterSale = x.split('=')[1];
        }
      });
      // this.afterSale = '10041002';
      //判断是否为车厂10461003
      // console.log(this.dataType,"dataType")
      if (this.dataType == 10461003) {
        // console.log(this.dataType,"车厂")
      }
    },
    sourceHandle() {
      this.visibleSource = true;
    },
    // 来源渠道清除
    clearSourceHandle() {
      this.clueSource = '';
      this.clueSourceName = '';
      this.initSourceForm.find(item => item.fieldName === 'clueSourceName').initialValue = '';
    },
    // 来源渠道关闭窗口 -返回数据
    closeSource(data) {
      console.log('-=-=-=-=-=-=-=', data);
      if (data.data && data.data.length > 0) {
        //循环返回数据
        let clueSourceArray = [];
        let clueSourceNameArray = [];
        data.data.forEach(x => {
          clueSourceArray.push(x.id);
          clueSourceNameArray.push(x.clueName);
        });
        this.clueSource = clueSourceArray.join(',');
        this.clueSourceName = clueSourceNameArray.join(',');
        //显示来源渠道名称
        this.initSourceForm.find(item => item.fieldName === 'clueSourceName').initialValue = this.clueSourceName;
      }
      //关闭弹窗
      this.visibleSource = data.visible;
    },

    //加载树
    async searchTree() {
      if (this.type1 == 'edit') {
        this.isDisables = false;
      }
      this.loading = true;
      let res = '';
      // let param = `employeeId=${this.rowData.employeeId}&dataSource=${this.rowData.dataSources}`;
      // console.log(this.UserData,"this.UserData.length")
      if (this.type1 != 'edit') {
        res = await userPermission(this.UserData.userOrgId, 10451001);
       this.userPermissionData = res.data.checkbox;
      } else {
        res = await userPermission(this.rowData.userOrgId, 10451001);
       this.userPermissionData = res.data.checkbox;
      }
      console.log(this.userPermissionData, '所有');
      localStorage.setItem('userPermissionData', this.userPermissionData.accessoriesWarehouse);
      // const resRole = await roleData(this.rowData.employeeId)
      let restree = res.data;
      // console.log(restree,"restree")
      //刷新权限管理---treejson找不到--by20190830
      console.log(restree,"retree:::");
      //默认勾选我的资料
      let downeTree = restree.treejson.find(x=>x.id==103025);
      if(!downeTree){
        downeTree = restree.treejson.find(x=>x.id==103015);
      }
      downeTree.state.checked = true;
      this.refreshMenut(restree);
      // const employeeRes = await findByEmployeeId(this.rowData.employeeId);
      // this.form = _.cloneDeep(employeeRes.data);
      // if (employeeRes.data.userCode === null) {
      //   this.userCodeShow = false;
      // }
      //职责复选框选中数据
      // this.employeeRolesCheck(this.rowData.employeeId);

      this.deleteRes(res.data.treejson);
      this.tree = res.data.treejson;
      this.loading = false;
      // 加载树
      this.getJsonTreeData();
    },
    getJsonTreeData() {
      this.tree.forEach(el => (el.label = el.text));
      this.tree.forEach(el => (el.parentId = el.parent));
      this.jsonTree = getJsonTree(this.tree);
      this.jsonTree = _.unionBy(this.jsonTree, 'id');
      // console.log(this.jsonTree,"this.jsonTree")
      // return getJsonTree(this.tree);
    },
    refreshMenut(restree) {
      /**
       * 勾选菜单
       */
      let restreejson = restree.treejson;
      let selectedmenu = [];
      for (let j = 0; j < restreejson.length; j++) {
        let states = restreejson[j].state;
        if (states.checked == true) {
          selectedmenu.push(restreejson[j].id);
        }
      }
      this.$refs['tree'].setCheckedKeys(selectedmenu);
      // 操作权限操作按钮
      this.checkListRoleMenuRange = restree.treeMenuRange;
      this.checkListRoleMenuAction = restree.treeMenuAction;
    },
    //职责复选框查询
    employeeRolesCheck(id) {
      const type = 1006;
      /*页面提示未定义。注释于20190826
      this.getEmployeeRoles(type); */
      // const checkedLists = [];
    },
    // 删除无效数据(无父节点)
    deleteRes(res) {
      let result = [];
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        let pid = res[i].parent;
        let oid = res[i].id;
        result[oid] = pid;
      }
      for (let j = 0; j < res.length; j++) {
        // 一级父节点跳过
        if (res[j].parent == '#') continue;
        if (res[j] && result[res[j].parent] == null) {
          let index = j;
          j = 0;
          delete result[res[index].id];
          res.splice(index, 1);
        }
      }
    },
    //树点击
    nodeClickHandle(data) {
      let { id, parent, text } = data;
      this.text = text;
      this.searchMenuHandle(id);
    },
    //显示客户信息操作权限
    async searchMenuHandle(id) {
      // console.log(id,"id")
      this.rangeloading = true;
      this.actionloading = true;
      this.menuId = id;

      //getRoleMenuRange
      const getRoleMenuRangeRes = await getRoleMenuRange(id, this.potOrgId);
      this.objRange = _.cloneDeep(getRoleMenuRangeRes.data);
      this.roleMenuRange = [];
      console.log(this.checkListRoleMenuRange, '权限配置单选');
      if (this.checkListRoleMenuRange != null) {
        /* for(let i=0;i<this.checkListRoleMenuRange.length;i++){
          console.log(this.checkListRoleMenuRange[i].split("-")[0],"权限配置单选1")
          if(id===this.checkListRoleMenuRange[i].split("-")[0]){
            console.log(this.checkListRoleMenuRange[i].split("-")[1],"权限配置单选2")
            this.roleMenuRange=Number(this.checkListRoleMenuRange[i].split("-")[1]);
          }
        } */
        for (let i = 0; i < this.checkListRoleMenuRange.length; i++) {
          if (id === this.checkListRoleMenuRange[i].split('-')[0]) {
            let rangArray = this.checkListRoleMenuRange[i].split('-')[1].split(',');
            for (let j = 0; j < rangArray.length; j++) {
              this.roleMenuRange.push(Number(rangArray[j]));
            }
            // return;
          }
        }
      }
      // getRoleMenuAction
      const getRoleMenuActionRes = await getRoleMenuAction(id, this.potOrgId);
      if (getRoleMenuActionRes.resultCode == 200) {
        this.rangeloading = false;
        this.actionloading = false;
      }
      this.objAction = _.cloneDeep(getRoleMenuActionRes.data);
      this.roleMenuAction = [];
      if (this.checkListRoleMenuAction != null) {
        for (let i = 0; i < this.checkListRoleMenuAction.length; i++) {
          if (id === this.checkListRoleMenuAction[i].split('-')[0]) {
            let actionArray = this.checkListRoleMenuAction[i].split('-')[1].split(',');
            for (let j = 0; j < actionArray.length; j++) {
              this.roleMenuAction.push(Number(actionArray[j]));
            }
            // return;
          }
        }
      }
      this.rangeloading = false;
      this.actionloading = false;
    },
    //操作权限改变事件
    handleRoleMenuRangeChange(value) {
      console.log(value, '456');
      /* this.checkListRoleMenuRange=[]
        this.checkListRoleMenuRange.push(this.menuId+"-"+value); */
      if (this.checkListRoleMenuRange != null && this.checkListRoleMenuRange.length > 0) {
        let ok = true;
        for (let i = 0; i < this.checkListRoleMenuRange.length; i++) {
          if (this.menuId === this.checkListRoleMenuRange[i].split('-')[0]) {
            if (value.length == 0) {
              this.checkListRoleMenuRange.splice(i, 1);
            } else {
              this.checkListRoleMenuRange[i] = this.menuId + '-' + value.join(',');
            }
            if (value.length > 1) {
              this.$message({
                type: 'info',
                message: '请单选!'
              });
            }
            /* if(value.length== 1){
              this.checkListRoleMenuRange[i]=this.menuId+"-"+value.join(",");
            }else{
              this.checkListRoleMenuRange.splice(i,1);
              this.checkListRoleMenuRange=[]
              this.$message({
                type: "info",
                message: "请单选!"
              });
            } */
            ok = false;
            return;
          }
        }
        if (ok) {
          this.checkListRoleMenuRange.push(this.menuId + '-' + value.join(','));
        }
      } else {
        this.checkListRoleMenuRange = [];
        this.checkListRoleMenuRange.push(this.menuId + '-' + value.join(','));
      }
    },
    //操作按钮改变事件
    handleRoleMenuActionChange(value) {
      if (this.checkListRoleMenuAction != null && this.checkListRoleMenuAction.length > 0) {
        let ok = true;
        for (let i = 0; i < this.checkListRoleMenuAction.length; i++) {
          if (this.menuId === this.checkListRoleMenuAction[i].split('-')[0]) {
            if (value.length == 0) {
              this.checkListRoleMenuAction.splice(i, 1);
            } else {
              this.checkListRoleMenuAction[i] = this.menuId + '-' + value.join(',');
            }
            ok = false;
            return;
          }
        }
        if (ok) {
          this.checkListRoleMenuAction.push(this.menuId + '-' + value.join(','));
        }
      } else {
        this.checkListRoleMenuAction = [];
        this.checkListRoleMenuAction.push(this.menuId + '-' + value.join(','));
      }
    },
    //职责选中事件1
    handleCheckedChange(value) {
      this.checkedList1 = this.checkedList1.concat(value);
      this.checkedList1 = _.uniq(this.checkedList1);
    },
    //职责选中事件2
    handleCheckedChange2(value) {
      this.checkedList2 = this.checkedList2.concat(value);
      this.checkedList2 = _.uniq(this.checkedList2);
    },
    //<!-- //CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START -->
    //职责选中事件1
    handleCheckedChangeAll(value) {
      this.checkedListAll = this.checkedListAll.concat(value);
      this.checkedListAll = _.uniq(this.checkedListAll);
    },
    //<!-- //CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END -->
    //分配权限保存
    async reqAuth() {
      console.log(this.clueSource, 'wwwwwwwwwwwwwwwwwwwwwwwwwwwww');
      console.log(this.checkListRoleMenuRange, 'this.rowData--reqAuth', this.checkListRoleMenuRange instanceof Array);
      if (this.checkListRoleMenuRange instanceof Array && this.checkListRoleMenuRange.length > 0) {
        this.checkListRoleMenuRange.forEach(x => {
          if (x.indexOf(',') > 0) {
            this.isRoleMenuRange = false;
          } else {
            this.isRoleMenuRange = true;
          }
        });
      } else {
        this.isRoleMenuRange = true;
      }

      if (this.isRoleMenuRange) {
        let selectedHalfNode = this.$refs['tree'].getCheckedKeys(); //父节点
        let selectedNode = this.$refs['tree'].getHalfCheckedKeys(); //子节点
        let allNode = selectedHalfNode.concat(selectedNode);
        if (allNode == '') {
          this.$message({
            type: 'info',
            message: '请至少分配一条权限!'
          });
        } else {
          //去掉一级菜单
          for (var k = 0; k < allNode.length; k++) {
            var nodekv = allNode[k];
            if (nodekv.length == 2) {
              allNode.splice(k, 1);
            }
          }
          console.log(this.rowData, 'this.rowData');
          let dataSalfe = {};
          if (this.afterSale == 10041001) {
            // dataSalfe = {
            //   // 配件仓库
            //   accessoriesWarehouse: this.$refs.storagePart.getData(),
            //   // 优惠模式
            //   favorableModels: this.$refs.favorableModels.getData(),
            //   // 结算
            //   checkedListSettlement: this.$refs.settlement.getData(),
            //   // 维修类型
            //   checkedListMaintenanceType: this.$refs.maintenanceType.getData(),
            //   // 仓库
            //   claimWarehouse: this.$refs.Warehouse.getData()
            // };
          }

          let params = {
            clueSourceIds: this.clueSource,
            clueSourceNames: this.clueSourceName,
            checkedList: this.checkedList1.concat(this.checkedList2),
            roleId: this.rowData == null ? '' : this.rowData.roleId,
            userOrgId: this.rowData == null ? this.UserData.userOrgId : this.rowData.userOrgId,
            nowTree: allNode.join(','),
            treeMenuRange: this.checkListRoleMenuRange.join(';'),
            treeMenuAction: this.checkListRoleMenuAction.join(';'),
            nowRole: this.rowData == null ? '' : this.rowData.roleId,
            // 维修
           // maintain: this.$refs.Todo.getData(),
            // 配件
           // accessories: this.$refs.part.getData(),
            //整车仓库
          //  vehicleWarehouse: this.$refs.storageVec.getData(),
            // 用品仓库
          //  suppliesWarehouse: this.$refs.storageJpck.getData(),
            ...dataSalfe
          };
          this.$refs['tree'].setCheckedKeys(selectedHalfNode);
          //const setRoleAuthRes = await setRoleAuth(this.rowData.roleId, params)
          // console.log(this.rowData,params,"this.rowData.roleId")
          this.saveLoading = true;
          const setRoleAuthRes = await saveRolePermission(params);
          if (setRoleAuthRes.resultCode == 200) {
            this.saveLoading = false;
            this.$notify.success({ title: '提示信息', message: '保存成功!' });
            this.closeDialog('refresh');
          } else {
            this.saveLoading = false;
            this.$notify.error({ title: '提示信息', message: setRoleAuthRes.errMsg || '保存失败!' });
            this.closeDialog();
          }
        }
      } else {
        this.$message({
          type: 'info',
          message: '客户信息中的操作权限请单选!'
        });
      }
    },

    //点击显示
    handleShow(type) {
      console.log(this.rowData, 'this.rowData', this.type1, type);
      this.$emit('handleShow', true, this.type1, this.rowData.orgId, this.rowData);
    },
    //关闭
    cancleHandle(data, dataTree) {
      this.visible = data;
      dataTree.forEach(el => (el.label = el.text));
      dataTree.forEach(el => (el.parentId = el.parent));
      this.jsonTree = getJsonTree(dataTree);
      this.jsonTree = _.unionBy(this.jsonTree, 'id');
    },
    //返回
    closeDialog(type) {
      this.$emit('close', false, type);
    }
  }
};
</script>

<style lang="less" scoped>
.el-checkbox + .el-checkbox {
  margin-left: 0px;
}

.el-checkbox {
  margin-right: 25px;
}
.dutyWrap {
  overflow: hidden;
  min-height: 200px;
}
.duty {
  width: 99%;
  height: 30px;
  line-height: 30px;
  margin-bottom: 5px;
  background: #eee;
  text-indent: 5px;
}
.menu-header {
  height: 30px;
  line-height: 30px;
  margin-bottom: 5px;
  background: #eee;
  text-indent: 5px;
}

.app-container .el-dialog__body {
  padding: 0 20px;
}
.padL10 {
  padding-left: 30px;
  // height: 50px;
  line-height: 50px;
}
.postH3 {
  cursor: pointer;
}
.postH3:hover {
  background: skyblue;
}
</style>
